// pages/add/add.js
const api = require('../../libs/api');

const app = getApp();
import {
  formatTime
} from '../../utils/util.js';
Component({

  /**
   * 组件的属性列表
   */
  properties: {
    give: {
      type: String
    },

    // button_text: {
    //   type: String,
    //   value: '保存'
    // },
    html: {
      type: String,
      value: ''
    }
  },

  /**
   * 页面的初始数据
   */
  data: {
    redirect:'',
    up:'1',
    title: '',
    id: '',
    center: [],
    slist: [], //存储所有选项
    isopen: true, //是否点击了文本
    istext:false,//判断是否有文字
    selected_function1: '文本',
    function1: ['文本', '待办', '插入'],
    wenben: [{
      img: './images/H1.png',
      text: '标题1',
      name: 'header',
      value: 1
    },
    {
      img: './images/H2.png',
      text: '标题2',
      name: 'header',
      value: 3
    },
    {
      img: './images/line.png',
      text: '分隔线'
    },
    {
      img: './images/B.png',
      text: '加粗',
      name: 'bold'
    },
    {
      img: './images/I.png',
      text: '斜体',
      name: 'italic'
    },
    {
      img: './images/U.png',
      text: '下划线',
      name: 'underline'
    },
    {
      img: './images/youxu.png',
      text: '编号',
      name: 'list',
      value: 'ordered'
    },
    {
      img: './images/wuxu.png',
      text: '列表',
      name: 'list',
      value: 'bullet'
    },
    {
      img: './images/left.png',
      text: '左对齐',
      name: 'align',
      value: 'left'
    },
    {
      img: './images/center.png',
      text: '居中',
      name: 'align',
      value: 'center'
    },
    {
      img: './images/right.png',
      text: '右对齐',
      name: 'align',
      value: 'right'
    },
    {
      img: './images/liangduan.png',
      text: '两端',
      name: 'align',
      value: 'justify'
    },
    ],
    charu: [{
      img: './images/settext.png',
      text: '文本'
    },
    {
      img: './images/photo.png',
      text: '图片'
    },
    {
      img: './images/wuxu.png',
      text: '待办',
      name: 'list',
      value: 'unchecked'
    },
    ],
    text: '', //获取文本内容
    getid: '', //获取分类id
    textcolor: 'rgb(235, 229, 229)',
    color: '#D0D0D0',
    imgFiles: [], //用于存储图片的临时路径
    start: '未分类',
    // slist: [{
    //   id: 1,
    //   name: "学习"
    // },
    // {
    //   id: 1,
    //   name: "生活"
    // },
    // {
    //   id: 1,
    //   name: "纪念日"
    // },
    // {
    //   id: 1,
    //   name: "其他"
    // },
    // ],
    isText: false,
    opn: false,
    isstart: false,
    openimg: "/images/label.png",
    offimg: "/images/label-on.png"
  },



  attached() {
    let pages = getCurrentPages();
    let prevpage = pages[pages.length - 2];

    var redirect = prevpage.route || ''
  
    this.getmenuType()
    // this.getnotepadData() 
    console.log(this.data.give)
    this.setData({
      function2: this.data.charu,
      redirect: redirect
    })

  },

  methods: {



    change_function1(e) {
      let selected = e.currentTarget.dataset.text;
      let {
        name,
        value
      } = e.currentTarget.dataset;
      console.log(selected)
      console.log(value)
      if (selected == '文本') {
        var function2 = this.data.wenben
        this.setData({
          selected_function1: selected,
          function2,
          isopen: false
        })
      } else if (selected == '图片') {
        this.insert_img()
      } else if (selected == '待办') {
        this.editorCtx.format(name, value);
      }






    },

    //编辑器初始化完成时触发
    onEditorReady() {
      console.log('编辑器初始化完成时触发')
      wx.showLoading({
        title: '加载中',
      }, 2000)
      // 返回一个 SelectorQuery 对象实例。在自定义组件或包含自定义组件的页面中，应使用this.createSelectorQuery()来代替。
      // https://developers.weixin.qq.com/miniprogram/dev/api/wxml/wx.createSelectorQuery.html 
      this.createSelectorQuery().select('#editor').context(res => {
        console.log('createSelectorQuery=>', res)
        this.editorCtx = res.context;
        this.getnotepadData()
        wx.hideLoading()
        // this.setContents(this.data.html); //设置富文本内容
      }).exec();

    },

    //设置富文本内容
    setContents(richtext) {

      console.log(richtext)
      this.editorCtx.setContents({
        html: richtext,
        success: res => {
          console.log('[setContents success--]', res)
        }
      })

    },

    // 通过 Context 方法改变编辑器内样式时触发，返回选区已设置的样式
    onStatusChange(res) {
      const formats = res.detail;
      var function2 = this.data.function2
      if (JSON.stringify(formats) == '{}') {//format为空时，清空所有选中
        for (var i = 0; i < function2.length; i++)function2[i]['selected'] = false
      }

      for (var i = 0; i < function2.length; i++) {//循环function2列表
        for (var key in formats) {//循环formats获取键值对
          if (function2[i]['name'] == key) {//function2中对name，对应formats中对键
            if (!function2[i]['value']) {//若function2中，只有name，没有value，则当name和key一样时，就是被选中
              function2[i]['selected'] = true
              break;//如果此function2是被选中的，那么就终止format循环，并判断下一个function2是否被选中
            }
            else if (function2[i]['value'] == formats[key]) {//function2中对value，对应formats中的值
              function2[i]['selected'] = true//值相等，肯定是被选中的
              break;
            }
            else {
              function2[i]['selected'] = false
            }
          }
          else {
            function2[i]['selected'] = false
          }
        }
      }
      this.setData({
        function2
      })

      // console.log('onStatusChange=>',formats,'\n',function2)
    },

    //每次点击功能栏时，都会触发此函数
    format(res) {
      let {
        name,
        value
      } = res.currentTarget.dataset;
      if (!name) {
        this.insert(res);
      }

      this.editorCtx.format(name, value);
    },

    insert(e) {
      var text = e.currentTarget.dataset.text
      if (text == "图片") {
        this.insert_img()
      } else if (text == "日期") {
        this.insert_date()
      } else if (text == "分隔线") {
        this.insert_line()
      }
    },

   
    undo() {
      this.editorCtx.undo();
    },

    redo() {
      this.editorCtx.redo();
    },

    insert_img() {
      var that = this;
      let imgFiles = that.data.imgFiles;
      wx.chooseImage({
        count: 1,
        success: res => {
          imgFiles = imgFiles.concat(res.tempFilePaths);
          console.log(imgFiles)
          that.setData({
            imgFiles
          })
          var path = res.tempFilePaths[0];
          this.editorCtx.insertImage({
            src: path,
            data: {
              id: 'imgage',
            },
          });
          //调用子组件方法，图片应先上传再插入，不然预览时无法查看图片。
          // that.insertImageMethod(path).then(res => {
          //   console.log('[insert image success callback]=>', res)
          // }).catch(res => {
          //   console.log('[insert image fail callback]=>', res)
          // });
        }
      })
    },
    insertImageMethod(path) {
      return new Promise((resolve, reject) => {
        this.editorCtx.insertImage({
          src: path,
          data: {
            id: 'imgage',
          },
          success: res => {
            resolve(res);
          },
          fail: res => {
            reject(res);
          }
        })
      })
    },


    
    //获取当前时间
    // insert_date(){
    //   const formatNumber = n => {
    //     n = n.toString()
    //     return n[1] ? n : '0' + n
    //   }

    //   const str_date=date=>{
    //     const year = date.getFullYear()
    //     const month = date.getMonth() + 1
    //     const day = date.getDate()
    //     const hour = date.getHours()
    //     const minute = date.getMinutes()

    //     return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute].map(formatNumber).join(':')
    //   }
    //   this.editorCtx.insertText({
    //     text:str_date(new Date())
    //   })
    // },

    insert_line() {
      this.editorCtx.insertDivider({
        success: res => {
          console.log('[insert line success]', res)
        }
      })
    },


    
    //获取判断文本框是否有文字
    getContenChange(e) {
      var that = this;

      console.log(e.detail.html)

      if (e.detail.text != null && e.detail.html != "<p><br></p>") {
        that.setData({
          textcolor: '#fff',
          color: 'orange',
          text: e.detail.text,
          istext:true
        })
      } else {
        that.setData({
          textcolor: 'rgb(235, 229, 229)',
          color: '#D0D0D0',
          istext:false
        })
      }

    },
    //点击显示下拉菜单
    opens: function (e) {
      console.log("你点了下拉菜单")
      switch (e.currentTarget.dataset.item) {
        case "1":
          if (this.data.isstart) {
            this.setData({
              isstart: false,
            });
          } else {
            this.setData({
              isstart: true,
            });
          }
          break;
      }
    },
    //点击分类菜单时触发
    onclicks1: function (e) {
      var index = e.currentTarget.dataset.index;
      let name = this.data.slist[index].notepadTypeName;
      let getid = this.data.slist[index]._id;
      console.log(getid);
      console.log(name);
      this.setData({
        getid: getid,
        opn: true,
        isstart: false,
        isfinish: false,
        isdates: false,
        start: name,
        finish: "目的地"
      })
    },
    cancel() {
      var function2 = this.data.charu
      this.setData({
        isopen: true,
        isstart: false,
        function2
      })
    },


    //发布数据
    async submitData(event) {
      //拿到用户填写的文本值
      let up = this.data.up
      let name = event.detail.value.noteName;
      let id = this.data.getid;
      let center = this.data.text;
      let s = [{
        notepadName: name,
        notepadTypeid: id,
        notesCenter: center
      }];
      console.log(this.data.give)
      let userinfo = wx.getStorageSync('userinfo');
      let openid = wx.getStorageSync('openid');
      var now = new Date();
      var hour = now.getHours(); //得到小时
      var minu = now.getMinutes(); //得到分钟
      var sec = now.getSeconds(); //得到秒
      var gtetime = now.getTime();
      var datetime = now.toLocaleString();
      var DATE = formatTime(new Date());
      console.log(gtetime)
      this.editorCtx.getContents({
        success: res => {
          
      let html = res.html
      if (this.data.istext==true && id != '' && up =='1'&&center != '\n') {
        if(id != '' && up =='1'&&center != '\n'){
        wx.showLoading({
          title: '正在上传',
        })
       

        /*** 上传数据库 ****/
        console.log(gtetime)

        api.callfun("add", {
          collectionName: "notepads",
          data: {
            center: center,
            notepadPic: '',
            notepadTypeid: id,
            title: name,
            _openid: openid,
            uptime: DATE,
            rank: gtetime,
            html:html,
            state:true
          }
        }).then(res => {
          wx.hideLoading()
          wx.showToast({
            title: '上传成功',
          })
          setTimeout(() => {
            wx.hideLoading()
            // app.updateConfigRequest()
            if (this.data.redirect != '') {
              wx.switchTab({
                url: '../../' + this.data.redirect,
              })
              console.log(this.data.redirect)
            } else {
              wx.switchTab({
                url: '../schedule/schedule',
  
              })
              console.log(this.data.redirect + '你好')
            }
          }, 1000)
        })



      }
      } //更新数据
      else if(this.data.give!=null&&this.data.give!=''&&center!=''&&center!=null&&this.data.istext==true){
      wx.showLoading({
        title: '正在上传',
      })
      console.log(this.data.give)
      api.callfun("updata",{
       where:{_id:this.data.give},
       data:{
         html:html,
         center: center,
         notepadPic: '',
         notepadTypeid: id,
         title: name,
         uptime: DATE,
         rank: gtetime
       },
       collectionName:"notepads"
     }).then(res => {
      wx.hideLoading()
      wx.showToast({
        title: '修改成功',
      })
      setTimeout(() => {
        wx.hideLoading()
        // app.updateConfigRequest()
        if (this.data.redirect != '') {
          wx.switchTab({
            url: '../../' + this.data.redirect,
          })
          console.log(this.data.redirect)
        } else {
          wx.switchTab({
            url: '../schedule/schedule',

          })
          console.log(this.data.redirect + '你好')
        }
      }, 1000)
    })
      } 
      else {
        app.msg('请输入内容并且选择类型')
      }
      console.log(s)
    }
  })
      //




    },



    //获取事件类型   （  生活 、 工作  、 纪念日  、 其他 ） 
    getmenuType() {
      api.find("notepadType").then(res => {
        this.setData({
          slist: res.data
        })
        console.log(res.data)


      })
    },


    //获取传进来的id数据
    getnotepadData() {
      console.log(this.data.give)
      let id = this.data.give;
      let where = { _id: id };
      if (id != null && id != '') {
        api.find('notepads', where).then(res => {
          let a = res.data[0].notepadTypeid
          switch (a) {
            case "0bcbdde05fca53bf00ae7e6d20b44837":
              this.setData({
                getid:"0bcbdde05fca53bf00ae7e6d20b44837",
                start: '生活',
                opn: true,
                textcolor: '#fff',
                color: 'orange',
              });
              break;
            case "e62469b25fca54a700deae655351d68d":
              this.setData({
                getid:"e62469b25fca54a700deae655351d68d",
                start: '工作',
                opn: true,
                textcolor: '#fff',
                color: 'orange',
              });
              break;
            case "0bcbdde05fca54e500ae861f506b7f8d":
              this.setData({
                getid:"0bcbdde05fca54e500ae861f506b7f8d",
                start: '学习',
                opn: true,
                textcolor: '#fff',
                color: 'orange',
              });
              break;
            case "0288fce75fca551100b7d78531a49c62":
              this.setData({
                getid:"0288fce75fca551100b7d78531a49c62",
                start: '其他',
                opn: true,
                textcolor: '#fff',
                color: 'orange',
              });
              break;
          }
          console.log(res.data[0]._id)
          let Detail = res.data[0];
          
          this.setContents(Detail.html);
          this.setData({
            text:Detail.center,
            center: res.data,
            up:'0',
            istext:true
          })

          console.log("结束")
        })


        wx.hideLoading({})
        // if(center.)
      }


    
    },


    //用户点击右上角分享
    onShareAppMessage: function () {

    }

  },
})